package com.campus.customer.service;

import com.campus.common.message.OrderCompleteMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 订单完成消息消费者
 * 监听Kafka中的订单完成消息，并发送微信订阅消息给顾客
 */
@Service
@Slf4j
public class OrderCompleteMessageConsumer {
    @Resource
    private ObjectMapper objectMapper;
    @Autowired
    private WechatSubscribeMessageService wechatSubscribeMessageService;

    /**
     * 监听订单完成消息
     * @param message 订单完成消息
     */
    @KafkaListener(topics = "order-complete", groupId = "customer-group")
    public void handleOrderCompleteMessage(String message) {
        OrderCompleteMessage orderCompleteMessage = null;
        try {
            orderCompleteMessage = objectMapper.readValue(message, OrderCompleteMessage.class);
            log.info("接收到订单完成消息，订单号: {}, 用户openId: {}", 
                    orderCompleteMessage.getOrderId(), orderCompleteMessage.getOpenId());
            
            // 发送微信订阅消息
            wechatSubscribeMessageService.sendOrderCompleteMessage(
                orderCompleteMessage.getOpenId(),
                orderCompleteMessage.getOrderId(),
                orderCompleteMessage.getGoodsName(),
                "¥" + orderCompleteMessage.getOrderAmount().toString(),
                orderCompleteMessage.getCompleteTime(),
                orderCompleteMessage.getRemark()
            );
            
            log.info("订单完成消息处理完成，订单号: {}", orderCompleteMessage.getOrderId());
            
        } catch (Exception e) {
            if(orderCompleteMessage == null){
                log.error("处理订单完成消息失败，消息内容: {}", message, e);
            }else{
                log.error("处理订单完成消息失败，订单号: {}, 用户openId: {}",
                        orderCompleteMessage.getOrderId(), orderCompleteMessage.getOpenId(), e);
            }
            // Kafka会自动重试，无需手动处理
        }
    }
}